<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
    <div class="wrapper">
      <div class="input-row">
        <el-form :inline="true" :model="formInline" @submit.native.prevent>
          <el-form-item label="关键词">
            <el-input size="small" clearable v-model="formInline.keyword" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item v-if="insertType === 'collect'" label="收藏分类">
            <el-select v-model="formInline.classifyId" size="small" placeholder="请选择" clearable>
              <el-option v-for="item in classifyList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="insertType === 'block'" label="结构化块分类">
            <el-cascader
              v-model="formInline.classifyId"
              :expand-trigger="'hover'"
              :options="cascaderData"
              :props="{ emitPath: false }"
              :show-all-levels="false"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" size="small">查询</el-button>
            <el-button @click="resetQuery" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" class="ins-table" max-height="500">
        <el-table-column prop="name" label="名字"> </el-table-column>
        <el-table-column prop="classifyId" label="分类"
          ><template slot-scope="scope">{{ getClassifyName(scope.row) }}</template>
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template slot-scope="scope"> <el-button type="text" size="mini" @click="insert(scope.row)">插入</el-button></template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total"
        layout="prev, pager, next"
        :page-size="10"
        :total="total"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-dialog>
</template>

<script>
import { v4 as uuid } from 'uuid'
import store from '@/store'
import tinymce from 'tinymce/tinymce'
import { getBlockTree } from '@/api/business'
import { getCollectListApi, getClassifyList } from '@/api'
import { getBlockInfoJSON, getBlockListApi } from '@/api'
import { Message } from 'element-ui'

export default {
  name: 'InsertDialog',
  data() {
    return {
      total: 0,
      currentPage: 1,
      tableData: [],
      cascaderData: [],
      blockTypeMap: {},
      formInline: {
        keyword: undefined,
        classifyId: undefined,
        standardName: undefined,
        description: undefined,
        nameZh: undefined
      },
      dialogVisible: false
    }
  },
  computed: {
    insertType() {
      return this.$store.state.xmleditor.insertType
    },
    title() {
      switch (this.insertType) {
        case 'collect':
          return '收藏'
        default:
          return '结构化块'
      }
    },
    classifyList() {
      return this.$store.state.xmleditor.classifyList
    }
  },
  methods: {
    resetQuery() {
      this.currentPage = 1
      this.formInline = {
        keyword: undefined,
        classifyId: undefined,
        standardName: undefined,
        description: undefined,
        nameZh: undefined
      }
      this.handleFilter()
    },
    show() {
      this.resetQuery()
      this.dialogVisible = true
    },
    async handleFilter(e) {
      if (e) {
        this.currentPage = 1
      }
      const _this = this
      const data = { ...this.formInline, pageSize: 10, pageNum: this.currentPage }
      let res
      if (this.insertType === 'collect') {
        getClassifyList()
        res = await getCollectListApi(data)
      } else if (this.insertType === 'block') {
        data.status = 1
        getBlockTree().then((res) => {
          function walk(obj) {
            const { children, id, name } = obj
            _this.blockTypeMap[id] = name
            if (children?.length) {
              return { label: name, value: id, children: children.map(walk), leaf: false }
            }
            return { label: name, value: id, leaf: true }
          }
          this.cascaderData = res?.data?.map(walk) || []
        })
        res = await getBlockListApi(data)
      }
      const { count, list, pageNum } = res
      this.total = count
      this.tableData = list
      this.currentPage = pageNum
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.handleFilter()
    },
    getClassifyName(row) {
      if (this.insertType === 'block') {
        return this.blockTypeMap[row.classifyId]
      }
      return this.classifyList.find((i) => i.id === row.classifyId)?.name || ''
    },
    async handleConfirm() {},
    async insert(row) {
      const currentNode = tinymce.activeEditor.selection.getNode()
      let data = []
      if (this.insertType === 'collect') {
        if (!row.jsonContent) {
          Message.error('错误的数据')
          return
        }
        data = JSON.parse(row.jsonContent)
      } else if (this.insertType === 'block') {
        data = await getBlockInfoJSON(row.id)
      } else {
        throw new Error()
      }
      // 为新插入内容设置 blockType
      const groupId = uuid()
      console.log('---SET_BLOCK_LIST---', data)
      store.commit('xmleditor/SET_BLOCK_LIST', data)
      setTimeout(() => {
        const type = this.insertType
        const dom = document.querySelector(`#blockList${type === 'collect' ? ' .group-block' : ''}`)
        dom.querySelectorAll('[data-id]').forEach((node) => {
          tinymce.activeEditor.dom.setAttribs(node, {
            'data-id': uuid(),
            'data-group-id': groupId,
            'data-block-type': this.insertType
          })
        })
        tinymce.activeEditor.insertContent(dom.innerHTML)
        store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
        this.handleClose()
        tinymce.activeEditor.notificationManager.open({
          timeout: 1500,
          text: '插入成功!',
          type: 'success'
        })
      })
    },
    handleClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.ins-table {
  width: 100%;
}
::v-deep .el-dialog {
  min-width: 800px;
}
::v-deep .el-dialog__body {
  padding-top: 0;
  padding-bottom: 10px;
}
</style>
